from drf_yasg.utils import swagger_auto_schema
from rest_framework import viewsets, status
from rest_framework import permissions
from rest_framework.response import Response
from .serializers import *
import AuthUtils
from user.models import Student, Clazz


class TaskViewSets(viewsets.ModelViewSet):
    queryset = CheckInTask.objects.all()
    permission_classes = (permissions.IsAuthenticated, )

    def get_serializer_class(self):
        if self.action in ['list', 'retrieve']:
            return TaskViewSerializer
        else:
            return TaskSerializer

    @swagger_auto_schema(operation_description="学生获得自己对应的所有打卡，管理员获得自己所管辖范畴的所有打卡")
    def list(self, request, *args, **kwargs):
        objs = None
        if AuthUtils.is_user_manager(request.user):
            objs = CheckInTask.objects.filter(clazz=request.user)
        elif AuthUtils.is_user_student(request.user):
            student = Student.objects.filter(user=request.user).get()
            objs = CheckInTask.objects.filter(
                manager__clazzs=student.clazz
            )
        data = TaskViewSerializer(instance=objs, many=True).data
        return Response(data=data, status=200)

    @swagger_auto_schema(operation_description="管理员发布打卡任务，非管理员拒绝请求，自动获取管理员id并写入")
    def create(self, request, *args, **kwargs):
        if AuthUtils.is_user_manager(request.user):
            request.data['manager'] = request.user.id
            serializer = self.get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            self.perform_create(serializer)
            headers = self.get_success_headers(serializer.data)
            return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
        else:
            return Response(data='没有相应的权限', status=403)

    @swagger_auto_schema(operation_description="获取某一打卡的详细信息，但拒绝不合法的查看")
    def retrieve(self, request, *args, **kwargs):
        if AuthUtils.is_user_manager(request.user):
            obj = CheckInTask.objects.filter(pk=kwargs['pk'])
            if obj.count() == 0:
                return Response(data='查询记录不存在', status=400)
            else:
                obj = obj.get()
            if obj.manager.user.id == request.user.id:
                return super().retrieve(request, *args, **kwargs)
            else:
                return Response(data='您无法查看其他管理员的发布', status=403)
        elif AuthUtils.is_user_student(request.user):
            obj = CheckInTask.objects.filter(pk=kwargs['pk'])
            if obj.count() == 0:
                return Response(data='查询记录不存在', status=400)
            else:
                obj = obj.get()
            user_clazz = Clazz.objects.filter(student__user=request.user).get()
            if obj.manager.clazzs == user_clazz:
                return super().retrieve(request, *args, **kwargs)
            else:
                return Response(data='不属于该用户的打卡任务，无法查看', status=403)
        else:
            return Response(data='身份未分配，请联系管理员', status=403)

    @swagger_auto_schema(operation_description="修改发布的任务")
    def update(self, request, *args, **kwargs):
        if AuthUtils.is_user_manager(request.user):
            task_id = self.get_serializer().data.id
            if CheckInTask.objects.filter(pk=task_id,manager__user=request.user):
                # 重新定位身份信息，防止冒充
                request.data['manager'] = request.user.id
                return super().update(request, *args, **kwargs)
            else:
                return Response(data='不属于管理范畴，无法修改', status=403)
        else:
            return Response(data='不具有对应权限，无法操作', status=403)

    @swagger_auto_schema(operation_description="删除已发布的任务")
    def destroy(self, request, *args, **kwargs):
        if AuthUtils.is_user_manager(request.user):
            task_id = self.get_serializer().data.id
            if CheckInTask.objects.filter(pk=task_id,manager__user=request.user):
                return super().destroy(request, *args, **kwargs)
            else:
                return Response(data='不属于管理范畴，无法修改', status=403)
        else:
            return Response(data='不具有对应权限，无法操作', status=403)


class StudentCheckViewSets(viewsets.ModelViewSet):

    permission_classes = (permissions.IsAuthenticated, )
    queryset = StudentCheckIn.objects.all()


